package kr.co.bnsmedia.touchconfig;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.View;

public class CalibrationActivity extends Activity implements View.OnClickListener, IOnHandlerMessage {

	private MyApp mApp = null;
	private WeakRefHandler mHandler = null;

	private CalibrationView mCalibration = null;

	private final int BUTTONS [] = {
			R.id.btn_start,
			R.id.btn_exit,
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calibration);

		for (int button : BUTTONS) {
			findViewById(button).setOnClickListener(this);
		}
		mCalibration = (CalibrationView)findViewById(R.id.vw_calibration);

		mApp = (MyApp)getApplication();
		mHandler = new WeakRefHandler((IOnHandlerMessage)this);
		mApp.setHandler(mHandler);

		mCalibration.setMyApp(mApp);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

	@Override
	public void onClick(View arg0) {
		final int fId = arg0.getId();

		switch (fId) {
		case R.id.btn_start:
			findViewById(R.id.ll_buttons).setVisibility(View.INVISIBLE);
			mCalibration.setStart(true);
			break;
		case R.id.btn_exit:
			setResult(RESULT_OK);
			finish();
			break;
		}
	}

	@Override
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case MyApp.HANDLER_RESULT:
			handlerResult(msg.arg1, msg.arg2, (byte[])msg.obj);
			break;
		case MyApp.HANDLER_EVENT:
			handlerEvent(msg.arg1, msg.arg2, (byte[])msg.obj);
			break;
		}
	}

	private void handlerResult(int aDev, int aDlen, byte[] aData) {
		int command = (int)(aData[0] & 0xFF);
		switch (command) {
		case g.command.SET_COEFFS:
			if (g.device.CAMERA2 == aDev) {
				mCalibration.setMyApp(mApp);
				findViewById(R.id.ll_buttons).setVisibility(View.VISIBLE);
				mCalibration.setStart(false);
			}
			break;
		}
	}

	private void handlerEvent(int aCmdDev, int aDlen, byte[] aData) {
		int command = (aCmdDev>>16) & 0xFFFF;
		int device = aCmdDev & 0xFF;

		switch (command) {
		case g.command.EVT_RADIAN_DATA:
			mCalibration.setData(device, aDlen, aData);
			break;
		}
	}
}
